<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item>监控管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/service' }">监控服务列表</el-breadcrumb-item>
            <el-breadcrumb-item>Prometheus服务配置</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 内容主体区 -->
        <div :style="innerStyle">

            <!-- 内容明细区 -->
            <div style="position: relative; display: flex;">
                <el-card shadow="hover" style="width: 400px; height: 265px;">
                    <el-form ref="prometheusFormRef" :model="prometheusForm" label-width="90px">
                        <el-form-item label="服务地址">
                            <el-link type="primary">{{url}}</el-link>
                        </el-form-item>
                        <el-form-item label="SSH端口号" style="margin-top:-20px;">
                            <span style="color: brown;">{{prometheusForm.ssh_port}}</span>
                        </el-form-item>
                        <el-form-item label="普通用户名" style="margin-top:-20px;">
                            <span style="color: brown;">{{prometheusForm.user_normal}}</span>
                        </el-form-item>
                        <el-form-item label="HOME路径" style="margin-top:-20px;">
                            <span style="color: brown;">{{prometheusForm.home_path}}</span>
                        </el-form-item>
                    </el-form>
                </el-card>
                <el-card shadow="hover" style="flex: 1; margin-left: 5px;" :body-style="{ padding: '0px' }">
                    <el-table :data="prometheusForm.targets" height="265" style="margin: 0px;" stripe>
                        <el-table-column prop="id" label="ID" width="50"></el-table-column>
                        <el-table-column prop="ipaddr" label="数据采集节点地址"></el-table-column>
                        <el-table-column prop="node_exporter_port" label="node_exporter 数据采集端口" width="200">
                            <template slot-scope="scope">
                                <el-tag v-if="scope.row.node_exporter_port <= 0" type="info" size="small" effect="dark" disable-transitions>
                                    未知
                                </el-tag>
                                <el-tag v-else type="success" size="small" effect="dark" disable-transitions>
                                    {{scope.row.node_exporter_port}}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="postgres_exporter_port" label="postgres_exporter 数据采集端口" width="220">
                            <template slot-scope="scope">
                                <el-tag v-if="scope.row.postgres_exporter_port <= 0" type="info" size="small" effect="dark" disable-transitions>
                                    未知
                                </el-tag>
                                <el-tag v-else type="success" size="small" effect="dark" disable-transitions>
                                    {{scope.row.postgres_exporter_port}}
                                </el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>

                <!-- 信息同步按钮 -->
                <div class="syncButtonGroup">
                    <el-popover
                        placement="left-start"
                        title="信息同步"
                        width="300"
                        trigger="hover"
                        content="以远程 prometheus.yml 配置文件为准，将信息同步覆盖到本地（一般用于处理本地与远程信息不同步导致的差异化问题）。">
                        <el-button slot="reference" size="mini" type="success" icon="el-icon-sort-down" :disabled="loadingJobs[0].code.length == 0" @click="syncDataFromYml" round plain>信息同步</el-button>
                    </el-popover>
                </div>
            </div>
            
            <!-- 内容配置区 -->
            <div style="height: calc(100% - 260px); margin-top: 5px;">
                <el-tabs v-model="fileName" style="height: 100%;" @tab-click="tabClick">
                    <el-tab-pane 
                        name="prometheus.yml" 
                        v-loading="loadingJobs[0].loading.enabled" 
                        :element-loading-text="loadingJobs[0].loading.text" 
                        element-loading-background="rgba(255, 255, 255, 1)">

                        <div class="tabButtonGroup">
                            <el-tooltip content="查找" placement="top-start">
                                <el-button size="mini" icon="el-icon-search" circle disabled></el-button>
                            </el-tooltip>
                            <el-tooltip content="编辑" placement="top-start">
                                <el-button size="mini" type="primary" icon="el-icon-edit" circle @click="dialogVisibleForPrometheusYmlEdit = true"></el-button>
                            </el-tooltip>
                            <el-tooltip content="刷新" placement="top-start">
                                <el-button size="mini" type="success" icon="el-icon-refresh" circle disabled></el-button>
                            </el-tooltip>
                            <el-tooltip content="恢复" placement="top-start">
                                <el-button size="mini" type="danger" icon="el-icon-magic-stick" circle disabled></el-button>
                            </el-tooltip>
                            <el-tooltip content="收藏" placement="top-start">
                                <el-button size="mini" type="warning" icon="el-icon-star-off" circle disabled></el-button>
                            </el-tooltip>
                        </div>

                        <span slot="label"><i class="el-icon-document"></i> prometheus.yml</span>
                        <div :style="`background: #F8F8F8; height: calc(${this.getInnerSize.height}px - 485px); overflow-y: scroll;`">
                            <highlightjs autodetect :code="loadingJobs[0].code" />
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>

        <!-- prometheus.yml 编辑框 -->
        <el-dialog
            title="编辑 prometheus.yml 配置文件"
            :visible.sync="dialogVisibleForPrometheusYmlEdit"
            width="90%"
            :show-close="false"
            :before-close="handleDialogClose">

            开发中，敬请期待 ...
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialogForPrometheusYml">取 消</el-button>
                <el-button type="primary" @click="commitDialogForPrometheusYml">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import { mapGetters } from 'vuex';
export default {
    data: function () {
        return {
            serviceId: 0,
            prometheusForm: {},
            fileName: '',
            filePath: '',
            url: '',

            loadingJobs: [
                {
                    name: 'prometheus.yml',
                    path: '',
                    loading: {
                        enabled: false,
                        text: ''
                    },
                    data: {},
                    code: ''
                }
            ],
            dialogVisibleForPrometheusYmlEdit: false
        }
    },
    mounted: async function () {
        const command = this.$route.query.command;
        const fragments = command.split('@');
        this.serviceId = fragments[0];
        this.filePath = fragments[1];
        this.fileName = fragments[2];

        // 先行加载用户传入的文件信息
        await this.queryServiceInfo();
        if (this.prometheusForm) this.tabClick();
    },
    computed: {
        ...mapGetters(['getInnerSize']),
        innerStyle: function () {
            return `height: ${this.getInnerSize.height - 160}px;`;
        },
    },
    methods: {
        queryServiceInfo: async function () {
            const result = await this.$http.get(`prometheus/${this.serviceId}`);
            const res = result.data;
            if (res.meta.status !== 201) return this.$message.error(`获取 Prometheus 数据源服务失败: ${res.meta.msg}`);

            this.prometheusForm = res.data;
            this.url = `http://${this.prometheusForm.ipaddr}:${this.prometheusForm.service_port}`;
            // console.log(this.prometheusForm);
        },
        tabClick: async function () {
            const job = this.loadingJobs.find(item => item.name === this.fileName);
            if (!job) return this.$message.error(`未知的配置文件名 ${this.fileName}`);
            if (job.data.jobid || job.loading.enabled) return;

            // 1.0 开启 UI 界面加载效果
            // console.log("Send download file request...", this.fileName);
            job.loading.enabled = true;
            job.loading.text = `正在获取配置文件 ${this.fileName} 的内容...`;

            // 2.0 请求下载配置文件
            const result = await this.$http.put(`prometheus/fetch`, {
                pid: this.serviceId,
                file_path: job.path,
                file_name: job.name
            });
            const res = result.data;
            if (res.meta.status !== 201) {
                job.loading.text = `请求获取 ${job.path}/${job.name} 配置文件发生错误: ${res.meta.msg}`;
                return;
            }
            job.data.jobid = res.data.job_id;
            this.fetchJobData(job);
        },
        fetchJobData: function (job) {
            setTimeout(async () => {
                const result = await this.$http.get(`process/${job.data.jobid}`);
                const res = result.data;
                if (res.meta.status !== 201) {
                    job.loading.text = `获取配置文件 ${job.fileName} 的下载结果失败：${res.meta.msg}`;
                    return;
                }
                job.data = res.data;

                // 任务如果非错误和完成状态，则循环监听任务回执消息
                const statusCode = res.data.status;
                if (statusCode !== -1 && statusCode !== 2) this.fetchJobData(job);
                else this.fetchJobFileContent(job);
            }, 1000);
        },
        fetchJobFileContent: async function (job) {
            const msg = job.data.steps[0].message;
            const fragments = msg.split('\n');
            const localFilePath = fragments[fragments.length - 1];
            if (job.data.status !== 2) {
                job.loading.text = localFilePath;
                return;
            }
            const result = await this.$http.get(`file/txt`, {
                params: {
                    local_file_path: localFilePath
                }
            });
            const res = result.data;
            if (res.meta.status !== 200) {
                job.loading.text = `读取配置文件 ${job.fileName} 的内容发生错误: ${res.meta.msg}`;
                return;
            }
            job.code = res.data.file_content;
            job.loading.enabled = false;
        },
        handleDialogClose: function () {},
        closeDialogForPrometheusYml: function () {
            this.dialogVisibleForPrometheusYmlEdit = false;
        },
        commitDialogForPrometheusYml: function () {
            console.log("Nothing...");
        },
        syncDataFromYml: async function () {
            const msg = this.loadingJobs[0].data.steps[0].message;
            const fragments = msg.split('\n');
            const localFilePath = fragments[fragments.length - 1];
            
            // console.log("localFilePath: ", localFilePath);
            const result = await this.$http.put(`prometheus/yml/sync`, {
                pid: this.serviceId,
                yml_file_path: localFilePath
            });
            const res = result.data;
            if (res.meta.status !== 201) return this.$message.error(`同步yml配置文件信息失败: ${res.meta.msg}`);

            this.$message.success(`同步yml配置文件信息完成`);
            this.queryServiceInfo();
        }
    }
}
</script>

<style lang="less" scoped>
    .syncButtonGroup {
        position: absolute;
        right: 30px;
        bottom: 15px;
    }

    .el-tab-pane {
        overflow: hidden;
        position: relative;
    }

    .tabButtonGroup {
        position: absolute;
        right: 30px;
        top: 15px;
    }
</style>
